<script>
import addtable from "@/mixins/addtable";
import AjaxStore from "@/utils/store/proxyAjax";
import store from "./store";
import { mapGetters } from "vuex";

export default {
  name: "activiti-task",
  mixins: [addtable, store],
  data() {
    return {
      tableOptWidth: "120",
      defaultItemsLength: 6,
      tableSelectionCol: false,
      autoLoad: false,
      taskId: "",
      claimTaskUrl: "/v1/activiti/task/claim", // 获取工作项
      clearAssigneeTaskUrl: "/v1/activiti/task/clearAssignee", // 释放工作项
      completeTaskUrl: "/v1/activiti/task/complete", // 完成工作项
      assigneeTaskUrl: "/v1/activiti/task/assignee", // 分配工作项
      delegateUrl: "/v1/activiti/task/delegate", // 委托工作项

      store: new AjaxStore({
        url: "/v1/activiti/task/query"
      }),
      columns: [
        {
          prop: "id",
          label: "工作项ID",
          sortable: true,
          "min-width": "140",
          "show-overflow-tooltip": true,
          "header-align": "center"
        },
        {
          prop: "name",
          label: "工作项名称",
          sortable: true,
          "min-width": "140",
          "show-overflow-tooltip": true,
          "header-align": "center"
        },
        {
          prop: "processDefinitionId",
          label: "流程ID",
          sortable: true,
          width: "240",
          "show-overflow-tooltip": true,
          "header-align": "center"
        },
        {
          prop: "processInstanceId",
          label: "流程实例ID",
          sortable: true,
          "min-width": "140",
          "show-overflow-tooltip": true,
          "header-align": "center"
        },
        {
          prop: "createTime",
          label: "启动时间",
          sortable: true,
          width: "155",
          "show-overflow-tooltip": true,
          "header-align": "center"
        },
        {
          prop: "claimTime",
          label: "认领时间",
          sortable: true,
          width: "155",
          "show-overflow-tooltip": true,
          "header-align": "center"
        },
        {
          prop: "assignee",
          label: "认领人",
          sortable: true,
          width: "120",
          "show-overflow-tooltip": true,
          "header-align": "center"
        }
      ],
      searchFields: [
        {
          label: "用户编号",
          prop: "userNo",
          placeholder: "请输入用户编号",
          anchor: 10
        },
        {
          label: "流程实例ID",
          prop: "processInstanceId",
          placeholder: "请输入流程实例ID",
          anchor: 9
        },
        {
          label: "业务关键字",
          prop: "processInstanceBusinessKey",
          placeholder: "请输入流程实例的业务关键字",
          anchor: 10
        },
        {
          label: "流程定义ID",
          prop: "processDefinitionKey",
          placeholder: "请输入流程定义ID",
          anchor: 9
        },
        {
          label: "流程定义名称",
          prop: "processDefinitionName",
          placeholder: "请输入流程定义名称",
          anchor: 10
        }
      ],
      searchModel: {
        userNo: "",
        processInstanceId: "",
        processInstanceBusinessKey: "",
        processDefinitionId: "",
        processDefinitionName: ""
      },
      searchBtnList: this.searchBtns,
      toolPanelBtnList: [],
      formPanel: {
        complete: {
          model: {
            name: "",
            businessKey: "",
            variables: ""
          },
          fields: [
            {
              label: "工作项",
              prop: "name",
              placeholder: "",
              xType: "text",
              anchor: 24,
              disabled: false
            },
            {
              label: "流程变量",
              prop: "variables",
              type: "textarea",
              rows: 5,
              anchor: 24,
              disabled: false,
              placeholder: `请输入对象，示例如下
{
  var1: “hello1”,
  var2: “hello2”
}`
            },
            {
              label: "备注",
              prop: "comment",
              placeholder: "请输入备注",
              type: "textarea",
              rows: 4,
              anchor: 24,
              disabled: false
            }
          ],
          rules: {},
          title: "完成工作项",
          type: "COMPLETE",
          ref: "completeForm",
          submitBtnList: this.completeTaskBtns
        },
        assignee: {
          model: {
            name: "",
            deptId: "",
            userNo: ""
          },
          fields: [
            {
              label: "受理部门",
              prop: "deptId",
              xType: "SelectConfig.deptId",
              isLocal: false,
              anchor: 24,
              ref: "deptment",
              filterable: true,
              relatedFields: ["userNo"],
              placeholder: "请选择负责团队",
              getData: () => {
                return this.request({
                  url: "/v1/dataProvider/getDeptmentList",
                  method: "get",
                  params: {
                    start: 1,
                    limit: 9999
                  }
                }).then(({ data }) => {
                  return data.map(item => {
                    return {
                      value: /^\d+$/.test(item.deptId)
                        ? parseInt(item.deptId)
                        : item.deptId + "",
                      label: item.deptName,
                      ...item
                    };
                  });
                });
              },
              on: {
                "visible-change": val => {
                  val && this.$refs.assigneeForm.$refs.deptment.load();
                }
              }
            },
            {
              label: "受理用户",
              prop: "userNo",
              placeholder: "请选择受理用户",
              xType: "SelectConfig.USER",
              multiple: false,
              filterable: true,
              anchor: 24,
              isLocal: false,
              ref: "userNo",
              autoLoad: false,
              on: {
                "el.form.update": (val, ctx, origin, form) => {
                  // 值,当前组件,关联组件
                  form.model.userNo = "";
                  ctx.load();
                },
                "visible-change": val =>
                  val && this.$refs.assigneeForm.$refs.userNo.load()
              },
              getData: () => {
                return this.request({
                  url: "/v1/sys/user/queryNoPaged",
                  method: "get",
                  params: {
                    q_deptId: this.formPanel.assignee.model.deptId
                  }
                }).then(({ data }) => {
                  if (this.formPanel.assignee.model.deptId) {
                    return data.map(item => {
                      return {
                        // value: /\d+/.test(item.codeValue) ? parseInt(item.codeValue) : item.codeValue,
                        value: /^\d+$/.test(item.userId)
                          ? parseInt(item.userId)
                          : item.userId + "",
                        label: item.userName,
                        ...item
                      };
                    });
                  } else {
                    return [];
                  }
                });
              }
            }
          ],
          rules: {
            deptId: [
              { required: true, message: "请选择受理部门", trigger: "blur" }
            ],
            userNo: [
              { required: true, message: "请选择受理用户", trigger: "blur" }
            ]
          },
          title: "分配工作项",
          type: "ASSIGNEE",
          ref: "assigneeForm",
          submitBtnList: this.assigneeTaskBtns
        }
      }
    };
  },
  computed: {
    ...mapGetters(["userNo"])
  },
  created() {
    this.searchModel.userNo = this.userNo;
  },
  mounted() {
    this.store._searchParams = { q_userNo: this.userNo };
    this.$refs.table.load(1, this.store.limit);
  },
  methods: {
    handleSearchReset() {
      this.$refs.searchForm.onReset();
      this.$set(this.$refs.searchForm.model, "userNo", "");
    },
    handleCompleteTaskSubmit() {
      const params = {};
      Object.assign(params, this.formPanel.complete.model);
      delete params.name;
      this.$refs.completeFormSubmitBtns.handleChangeStatus(
        "handleCompleteTaskSubmit",
        { loading: true, icon: "" }
      );
      this.completeTask(Object.assign(params, { taskId: this.taskId }))
        .then(({ success, message }) => {
          this.$refs.completeFormSubmitBtns.handleChangeStatus(
            "handleCompleteTaskSubmit",
            { loading: false, icon: "" }
          );
          this.$message({
            type: success ? "success" : "error",
            message
          });
          if (success) {
            this.dialogType = "";
            this.$refs.table.load(1);
          }
        })
        .catch(err => console.log(err));
    },
    // 完成工作项
    handleCompleteTask(row) {
      this.dialogType = "COMPLETE";
      this.taskId = row.id;
      this.$nextTick(() => {
        this.$refs.completeForm && this.$refs.completeForm.resetFields();
        this.$set(this.formPanel.complete.model, "name", row.name);
      });
    },
    // 获取工作项
    handleClaimTask(row) {
      this.claimTask({ taskId: row.id })
        .then(({ success, message }) => {
          this.$message({
            type: success ? "success" : "error",
            message
          });
          if (success) {
            this.$refs.table.load(1);
          }
        })
        .catch(err => console.log(err));
    },
    // 释放工作项
    handleClearAssigneeTask(row) {
      this.clearAssigneeTask({ taskId: row.id })
        .then(({ success, message }) => {
          this.$message({
            type: success ? "success" : "error",
            message
          });
          if (success) {
            this.$refs.table.load(1);
          }
        })
        .catch(err => console.log(err));
    },
    // 分配工作项
    handleAssigneeTask(row) {
      this.dialogType = "ASSIGNEE";
      this.taskId = row.id;
      this.$nextTick(() => {
        this.$refs.assigneeForm && this.$refs.assigneeForm.resetFields();
      });
    },
    handleAssigneeTaskSubmit() {
      return this.$refs.assigneeForm
        .validate()
        .then(() => {
          this.$refs.assigneeFormSubmitBtns.handleChangeStatus(
            "handleAssigneeTaskSubmit",
            { loading: true, icon: "" }
          );
          const params = {};
          params.taskId = this.taskId;
          params.userNo = this.formPanel.assignee.model.userNo;
          return this.assigneeTask(params);
        })
        .then(({ success, message }) => {
          this.$refs.assigneeFormSubmitBtns.handleChangeStatus(
            "handleAssigneeTaskSubmit",
            { loading: false, icon: "" }
          );
          this.$message({
            type: success ? "success" : "error",
            message: message
          });
          if (success) {
            this.$refs.table.load(1);
            this.$refs.assigneeForm && this.$refs.assigneeForm.resetFields();
          } else {
            throw new Error(message);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // eslint-disabled-next-line
    renderWrapTable(h) {
      return (
        <WrapTable
          ref="table"
          getData={this.getData}
          total={this.total}
          data={this.data}
          fields={this.columns}
          selectionCol={this.tableSelectionCol}
          indexCol={this.tableIndexCol}
          pagination={this.pagination}
          autoLoad={this.autoLoad}
          tooltip-effect="dark"
          border
          stripe
          default-sort={this.tableDefaultSort}
          on-selection-change={this.handleSelectionChange}
        >
          {this.searchBtnList && this.searchBtnList.length > 0 ? (
            <SearchForm
              items={this.searchFields}
              defaultItemsLength={this.defaultItemsLength}
              props-model={this.searchModel}
              slot="searchPanel"
              ref="searchForm"
            >
              <ButtonList
                operateBtnList={this.searchBtnList}
                props-model={this.searchModel}
              ></ButtonList>
            </SearchForm>
          ) : (
            ""
          )}

          <c-row slot="toolPanel" class="toolPanel">
            <c-col
              span={this.btnListWidthPercent}
              offset={this.btnListWidthOffset}
            >
              <ButtonList operateBtnList={this.toolPanelBtnList}></ButtonList>
            </c-col>
          </c-row>

          {this.haveTool ? (
            <c-table-column
              label="操作"
              align="center"
              slot="toolbar"
              fixed="right"
              width={this.tableOptWidth}
              {...{
                scopedSlots: {
                  default: scope => {
                    return (
                      <TableButtonList
                        operateBtnList={this.tableRowBtns}
                        props-model={scope.row}
                      />
                    );
                  }
                }
              }}
            />
          ) : (
            ""
          )}
        </WrapTable>
      );
    }
  },
  beforeCreate() {
    // 根据页面路由找出有权限访问的 url 数组
    const urlArr = ((this.$route.meta && this.$route.meta.children) || []).map(
      item => item.url
    );

    this.searchBtns = [
      {
        label: "查询",
        methods: "handleSearch",
        url: "/v1/activiti/task/query",
        icon: "el-icon-search",
        type: "primary",
        disabled: false
      },
      {
        label: "重置",
        methods: "handleSearchReset",
        url: "",
        icon: "el-icon-refresh",
        type: "warning",
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url);

    this.tableRowBtns = [
      {
        label: "完成工作项",
        methods: "handleCompleteTask",
        url: "/v1/activiti/task/complete",
        icon: "el-icon-circle-check-outline",
        type: "primary",
        key: "start",
        align: "top-start",
        disabled: false
      },
      {
        label: "获取工作项",
        methods: "handleClaimTask",
        url: "/v1/activiti/task/claim",
        svgIcon: "claimTask",
        type: "danger",
        key: "delete",
        align: "top-start",
        disabled: false
      },
      {
        label: "释放工作项",
        methods: "handleClearAssigneeTask",
        url: "/v1/activiti/task/clearAssignee",
        svgIcon: "clearAssigneeTask",
        type: "primary",
        key: "delete",
        align: "top-start",
        disabled: false
      },
      {
        label: "分配工作项",
        methods: "handleAssigneeTask",
        url: "/v1/activiti/task/assignee",
        svgIcon: "assigneeTask",
        type: "primary",
        key: "delete",
        align: "top-start",
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url);

    this.completeTaskBtns = [
      {
        label: "提交",
        methods: "handleCompleteTaskSubmit",
        url: "/v1/activiti/task/complete",
        icon: "el-icon-circle-check-outline",
        type: "primary",
        disabled: false
      },
      {
        label: "取消",
        methods: "handleCancel",
        url: "",
        icon: "el-icon-circle-close-outline",
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url);

    this.assigneeTaskBtns = [
      {
        label: "提交",
        methods: "handleAssigneeTaskSubmit",
        url: "/v1/activiti/task/complete",
        icon: "el-icon-circle-check-outline",
        type: "primary",
        disabled: false
      },
      {
        label: "取消",
        methods: "handleCancel",
        url: "",
        icon: "el-icon-circle-close-outline",
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url);
  }
};
</script>

<style lang="scss">
.activiti-task {
  box-sizing: border-box;
  .searchPanel {
    padding-bottom: 0;
    .search-btn-box {
      bottom: 0;
    }
  }
  .el-col {
    &:nth-child(1) {
      .el-form-item__label {
        min-width: 94px;
      }
    }
    &:nth-child(3) {
      .el-form-item__label {
        min-width: 94px;
      }
    }
  }
  .el-icon-circle-check-outline {
    color: #3f9eff;
  }
}
</style>
